package com.cy.http;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpContext {
    private static Map<String,String> mimeTypeMapping = new HashMap<>();
    private static Map<Integer,String> statusCodeReasonMapping = new HashMap<Integer,String>();
    static {
        initMimeTypeMapping();
        initStatusCodeReasonMapping();
    }

    private static void initStatusCodeReasonMapping() {
        statusCodeReasonMapping.put(200, "OK");
        statusCodeReasonMapping.put(201, "Created");
        statusCodeReasonMapping.put(202, "Accepted");
        statusCodeReasonMapping.put(204, "No Content");
        statusCodeReasonMapping.put(301, "Moved Permanently");
        statusCodeReasonMapping.put(302, "Moved Temporarily");
        statusCodeReasonMapping.put(304, "Not Modified");
        statusCodeReasonMapping.put(400, "Bad Request");
        statusCodeReasonMapping.put(401, "Unauthorized");
        statusCodeReasonMapping.put(403, "Forbidden");
        statusCodeReasonMapping.put(404, "Not Found");
        statusCodeReasonMapping.put(500, "Internal Server Error");
        statusCodeReasonMapping.put(501, "Not Implemented");
        statusCodeReasonMapping.put(502, "Bad Gateway");
        statusCodeReasonMapping.put(503, "Service Unavailable");
    }

    private static void initMimeTypeMapping() {
        //读取文件，maven中的config文件从里面获取文件类型
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("conf/web.xml");
            Element root = doc.getRootElement();
            List<Element> elements = root.elements("mime-mapping");
            for (Element ele : elements) {
                String key = ele.elementText("extension");
                String value = ele.elementText("mime-type");
                mimeTypeMapping.put(key, value);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static String getMimeType(String ext) {
        return mimeTypeMapping.get(ext);
    }

    public static String getStatusReason(int statusCode) {
        return statusCodeReasonMapping.get(statusCode);
    }
}
